package hk.edu.polyu.comp.motioncapture.userApplication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Sender {
	ServerSocket serverSocket = null;

	Socket clientSocket = null;

	PrintWriter out;

	BufferedReader in;
	
	final int port = 43419;

	
	/**
	 * Start the connection with the client application
	 * The connection enable to send the command throw the socket data
	 */
	public void startConnection()
	{
		try {
			serverSocket = new ServerSocket(port);

			clientSocket = serverSocket.accept();

			out = new PrintWriter(clientSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(clientSocket
					.getInputStream()));

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Send the command to the user application throw the socket
	 * @param command Command of the action   
	 */
	public void sendCommand(String command) {
		try {
			out.println(command);

		} catch (Exception e) {
			// e.printStackTrace();
		}
	}

	/**
	 * Close the connection between the Java Server and the client application
	 */
	public void closeSender() {
		try {
			out.close();
			in.close();
			clientSocket.close();
			serverSocket.close();

			System.out.println("Closed...");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Return the point number of the connection
	 * @return Port number
	 */
	public int getPort()
	{
		return port;
	}
	
	
	public static void main(String args[]) {
		Sender sender = new Sender();

		try {
			for (int i = 0; i < 6; i++) {
				sender.sendCommand("Command  " + i);
				Thread.sleep(1000);
			}
			sender.closeSender();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}